package com.mobileservice.autoreply.receiver;

import com.mobileservice.autoreply.activity.ReceiveSMSActivity;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

public class TextMessageReceiver extends BroadcastReceiver {

	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();

		Object[] messages = (Object[]) bundle.get("pdus");
		SmsMessage[] sms = new SmsMessage[messages.length];

		for (int n = 0; n < messages.length; n++) {
			sms[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
		}

		for (SmsMessage msg : sms) {

			String phoneNumber = msg.getOriginatingAddress();
			String msgBody = msg.getMessageBody();
			ReceiveSMSActivity.updateMessageBox("\nFrom: " + phoneNumber + "\n" + "Message: " + msgBody + "\n");
			if (phoneNumber.length() > 0 && msgBody.length() > 0) {
				PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, TextMessageReceiver.class), 0);
				SmsManager smsManager = SmsManager.getDefault();
				smsManager.sendTextMessage(phoneNumber, null, msgBody, pi, null);
			}

		}
		abortBroadcast();
	}
}